/*
** https://github.com/google/web-starter-kit
** view-source:http://biz.ifeng.com/gongyi/special/derucci20153g/index.shtml
**/


//import `babel-register`;
//import `babel-polyfill`;
const gulp = require('gulp');
const path = require('path');
const fs = require('fs');
const globalLoadPlugin = require('gulp-load-plugins');
const frontMatter = require('gulp-front-matter');
const del = require('del');
const runSequence = require('run-sequence');
const cleanCSS = require('gulp-clean-css');
const sourcemaps = require('gulp-sourcemaps');
//const data = require('gulp-data');


const $ = globalLoadPlugin();

const ROOT = path.resolve(`${__dirname}`,'../../../');
const pathVars = {
	LIBS:`${ROOT}/node_modules`
}
const eslintConfig ={
	rules:{
        "camelcase": 1,
        "comma-dangle": 2,
        "quotes": 0,
        //"no-multiple-empty-lines": [0, {"max": 100}],
        //"no-mixed-spaces-and-tabs": [0],
    },
	globals: [
        'jQuery',
        '$'
    ],
    envs: [
        'browser'
    ]
}

//lib assets
const ASSETS_LIST = {
	css: {
			swiper: "swiper/dist/css/swiper.css",
			animatelo: "animate.css/animate.css",
			fontAwesome:"Font-Awesome/css/font-awesome.css"
			//fullpage:"fullpage.js/dist/jquery.fullpage.css",
		},
	js: {
			jquery:'jquery/dist/jquery.js',
			swiper:"swiper/dist/js/swiper.jquery.js",

		},
	fonts:{
		fontAwesome:"Font-Awesome/fonts/**.*"
	}

};




gulp.task('clear',cb=>{

	//gulp的task默认是异步执行，加return后才是同步执行。
	let result =  del('./dist');

	cb = ()=>{
	   console.info('CLEAR::===================================clear dist===================================');
	}

	cb();
	return result;
});

/*
gulp.task('compile-page',cb=>{
	gulp.src('./src/data_in_page.html')
	  .pipe(frontMatter({ property: 'data' }))
      .pipe($.swig())
      .pipe(gulp.dest('dist'));

    cb();

    function cb(){
    	console.log('template is completed compiled!');
    }

});
*/


//prepare assets for use
gulp.task('prepare-assets',cb=>{
    let result;

	for(let key in ASSETS_LIST){
		let list = Object.values(ASSETS_LIST[key]).map((item)=>{
			return path.resolve(pathVars.LIBS,item);
		});
		let condition = key!=='fonts';

		new Promise(
			(resolve,reject)=>{
				result =  gulp.src(list)
				.pipe($.if(condition,$.rename({prefix: "_"})))
				.pipe(gulp.dest(`dist/${key}`));

				cb();
				//return result;
				function cb(){
					resolve(`assets:[ ${key} ] is completed prepared!`);
				}
			}
		).then((msg)=>{
			console.log(msg);
			//return result;
		}); 

	};

	cb = function(){
		console.info('PREPARE-ASSETS:===================================prepare-assets===================================');
	}

	cb();

	//return stream for run-sequence useing
	return result;
	
});


gulp.task('build:lib-css',cb=>{
	return gulp.src('./dist/css/_*.css')
		.pipe(sourcemaps.init())
		.pipe($.concat('all.min.css'))
		.pipe(cleanCSS({debug: true}, function(details) {
      		//console.log(details.name + ': ' + details.stats.originalSize);
      		//console.log(details.name + ': ' + details.stats.minifiedSize);
    	}))
    	.pipe($.size({title:'style'}))
		.pipe(sourcemaps.write())
		.pipe(gulp.dest(`${ROOT}/dist/themes/b-elegant/css`));
});

gulp.task('build:lib-js',cb=>{
	return gulp.src('./dist/js/_*.js')
		.pipe(sourcemaps.init())
		.pipe($.concat('bundle.min.js'))
		.pipe($.uglify())
		.pipe($.size({title:'script'}))
		.pipe(sourcemaps.write())
		.pipe(gulp.dest(`${ROOT}/dist/themes/b-elegant/js`));
});


gulp.task('build:theme-css',cb=>{
	let result = gulp.src('scss/*.scss');
	cb();
	function cb(){
		console.info('THEME:CSS: =================================== build:theme-css ===================================')
	}
	return result;
});

gulp.task('build:theme-script',cb=>{
	let result = gulp.src(['src/*.js','!src/_*.js'])
		.pipe($.eslint(eslintConfig))
		.pipe($.eslint.format())
		.pipe($.eslint.failAfterError())
		.pipe($.sourcemaps.init())
		.pipe($.babel())
		.pipe($.uglify())
		.pipe($.sourcemaps.write())
		//.pipe($.rename(prefix: "_"))
		.pipe(gulp.dest(`${ROOT}/dist/themes/b-elegant/js`));


	cb();
	function cb(){
		console.info('THEME:SCRIPT: =================================== build:theme-script ===================================')
	}
	return result;
});

gulp.task('optimize-images',cb=>{

	let result = gulp.src('./images/');

	cb();
	function cb(){
		console.info('OPTIMIZE-IMAGES: =================================== optimize-images ===================================')
	}

	return result;
});





gulp.task('data-from-json',[],cb=>{
	let sources = gulp.src(['dist/js/bundle.min.js', 'dist/css/all.min.css'], {read: false});


	let result = gulp.src('./src/index.html')
	    .pipe($.data(()=>{
	    	return JSON.parse(fs.readFileSync('./src/data.json'))
	    }))
	    .pipe($.swig())
	    .pipe($.inject(sources,{relative:true,removeTags:true/*,addRootSlash:false,addPrefix:'..'*/}))
	    .pipe(gulp.dest('dist'));

	cb();

	return result;

	function cb(){
		//listFiles('./dist/js/');
    	console.info('TAMPLATE:=================================== compile template ===================================');


    }
});

gulp.task('build',['build:theme-script'],cb=>{
	let result = gulp.src(['dist/**/*','!dist/**/_*'])
	      .pipe(gulp.dest(`${ROOT}/dist/themes/b-elegant`));

	cb();
	function cb(){
		console.info('BUILD:COPY: =================================== Copy all files at the root level ===================================')
	}

	return result;
})


gulp.task('default',cb=>{
	//make sure they either return a stream or promise, or handle the callback
	runSequence('clear',['prepare-assets'],['build:lib-css','build:lib-js','build:theme-css','build:theme-script','optimize-images'],'data-from-json',cb);
	//console.log('build is completed!');
	function cb(){
		console.info('build themes completed!');
	}
});






function listFiles(path){
	fs.readdir(path,(err,files)=>{
		console.log(files);

	});
}